#!/bin/sh
# Copyright (c) 2012, bkil.hu
# This program is free software and can be distributed under the terms of
# the GNU General Public License v2,
# see COPYING for detailed licensing terms.

# created on 2012-12-06

main() {
 CHANNELS="$HOME/hbo-scan.txt" # generate with w_scan, etc.

 if
  ! zap1 -x
 then
  echo "error: tzap" >&2
  exit 1
 fi

 zap1 2>&1 |
 grep --line-buffered "|" | # parse only data rows
 while read X STATUS B X SIGNAL B X SNR B X BER B X UNC B LOCK; do
  printf "%s " `date +%H:%M:%S.%N`
  echo "st $STATUS sig $SIGNAL SNR $SNR BER $BER UNC $UNC $LOCK"
  local DSIGNAL=`printf "%d" 0x$SIGNAL`
  local DBER=`printf "%d" 0x$BER`
  local DBER=`expr $DBER / 10`
  if ! [ "$LOCK" = "FE_HAS_LOCK" ] ; then
   signal 0 # "Lock."
  elif ! [ "$UNC" = "00000000" -o "$UNC" = "ffffffff" ] ; then
   signal 0 # "Uncorrect."
  else
   if [ "$BER" = "00000000" ] ; then
    signal `expr 2000 + $DSIGNAL / 16` # OK
   elif ! [ "$SNR" = "ffff" ] ; then
    signal -1 # "R $DBER"
   else
    if [ $DBER -gt 881 ] ; then
     signal -1 # $DBER>=100
    else
     signal `expr 120 + $DBER - 1`
    fi
   fi
  fi
 done
}

zap1() {
 real_zap "$@"
# mock_zap "$@"
}

mock_zap() {
 if [ "$1" != "-x" ]; then
  cat << EOF |
status 1f | signal 9999 | snr ffff | ber 000012b0 | unc 00000000
status 1f | signal 9999 | snr fffe | ber 000012b0 | unc 00000001 | FE_HAS_LOCK
status 1f | signal 9999 | snr fffe | ber 000012b0 | unc 00000000 | FE_HAS_LOCK
status 1f | signal 9999 | snr ffff | ber 000012b0 | unc 00000000 | FE_HAS_LOCK
status 1f | signal 9999 | snr ffff | ber 00000000 | unc 00000000 | FE_HAS_LOCK
status 1f | signal 9a9a | snr ffff | ber 00000000 | unc 00000000 | FE_HAS_LOCK
EOF
   while read LINE;do
    echo "$LINE"
    sleep 1
    echo "$LINE"
    sleep 1
   done
 fi
}

real_zap() {
 if [ "$1" = "-x" ]; then
  tzap -F -c $CHANNELS "RTL Klub" "$@"
 else
  while true
  do
   for CHANNEL in "RTL Klub" "Duna World"
   do
    say "$CHANNEL" &
    tzap -F -c $CHANNELS "$CHANNEL" "$@" &
    local ZAP=$!
    sleep 15
    kill $ZAP
    while kill -0 $ZAP; do
     sleep 0.1
    done
   done
  done
 fi
}

signal() {
 F=$1
 SIGS="2 3 4 7 8 9 11 15"
 [ $F -eq -1 ] && F=1000
 [ -n "$PID" ] && kill $PID
# echo $F
 if [ $F -gt 0 ]; then
  speaker-test -t sine -f $F >/dev/null &
  PID=$!
  trap "kill $PID" $SIGS
 else
  PID=""
  trap - $SIGS
 fi
# say "$@"
}

say() {
 [ -n "$PID" ] && kill $PID
 espeak -z -v english_rp+klatt2 "$@" 2>/dev/null
}

main "$@"

